<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        .shadow {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 50px;
            top: 50px;
            text-align: center;
            line-height: 200px;
            user-select: none;
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="shadow">1</div>
    <div class="shadow">2</div>
    <div class="shadow">3</div>
    <div class="shadow">4</div>
    <div class="shadow">5</div>
    <div class="shadow">6</div>
</body>
<script>

    class DragEle {

        posX = null;
        posY = null;

        constructor(ele) {
            this.target = ele;
            this.dragStart();
        }

        dragStart() {
            // this -> 调用此方法的实例化对象
            // 先按下 => 记录按下的位置

            var _this = this; // this->调用此方法的实例化对象(引用类型)

            this.target.onmousedown = function (e) {// 事件中的this指向绑定事件的元素(target=> shadow)
                var e = e || window.event;
                var posX = e.offsetX;
                var posY = e.offsetY;
                console.log(_this, posX, posY);

                _this.posX = posX;
                _this.posY = posY;

                // 按下时绑定 移动和松开事件
                _this.dragMove();
                _this.dragEnd();
            }
        }
        dragMove() {
            // this -> 调用此方法的实例化对象

            // 2.  盒子跟随鼠标在文档中移动
            document.onmousemove = (e) => { // 箭头函数没有自己的this指向  this->它的this依赖于包裹箭头函数的作用域的this(父作用域)   this -> 调用此方法的实例化对象
                console.log(111111);
                var e = e || window.event;

                var x = e.pageX - this.posX;
                var y = e.pageY - this.posY;

                this.target.style.left = x + "px";
                this.target.style.top = y + "px";
            }

        }
        dragEnd() {
            // this -> dragEle
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }
    }

</script>

</html>